

import 'package:sqflite/sqlite_api.dart';
import 'package:xreader/common/app_config.dart';
import 'package:xreader/db/base_db_provider.dart';
import 'package:xreader/logs/log.dart';
import 'package:xreader/model/t_sys_entity.dart';

class TSysProvider extends BaseDbProvider{
  static final String TABLE_NAME = AppConfig.t_sys;
  static final String column_scode= "scode";
  static final String column_svalue = "svalue";
  Map<String,dynamic> toMap(TSysEntity po){
    Map<String,dynamic> info = {
      column_scode:po.scode,
      column_svalue:po.svalue,
    };
    return info;
  }
  @override
  String tableName() {
    return TABLE_NAME;
  }

  @override
  String tableSqlString() {
    String createSql = '''${tableBaseStringTextPrimarkKey(TABLE_NAME, column_scode)}        
          $column_svalue text
     )
      ''';
    Log.i(createSql);
    return createSql;
  }

  ///insertOrUpdateBatch
  insertOrUpdateBatch(List<TSysEntity>? datas) async {
      if(datas == null || datas.isEmpty){
        return;
      }
      Database? db = await getDataBase();
      if(db == null){
        return;
      }
      var batch = db.batch();
      datas.forEach((info) {
        batch.insert(TABLE_NAME, toMap(info),conflictAlgorithm: ConflictAlgorithm.replace);
      });
      await batch.commit(noResult: true);
  }

  //根据主键获取
  Future<TSysEntity> getByScode(String scode) async {
    TSysEntity po = TSysEntity();
    Database? db = await getDataBase();
    if(db == null){
      return po;
    }
    List<Map<String,Object?>> datas = await db.rawQuery("select * from $TABLE_NAME where scode = ? ",[scode]);
    for(Map<String,Object?> data in datas){
      return TSysEntity.fromJson(data);
    }
    return po;
  }

  //判断是否是否需要同步
  Future<bool> checkNeedSync(String updateSign) async {
    TSysEntity po = await getByScode(AppConfig.T_SYS_UPDTAE_SIGN);
    return (po.svalue ?? "").compareTo(updateSign) != 0;
  }

}